package com.bilibili.server.repository;

import com.bilibili.server.entity.Video;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Optional;
import java.util.List;

@Repository
public interface VideoRepository extends JpaRepository<Video, Long> {
    Page<Video> findByStatus(Integer status, Pageable pageable);
    Page<Video> findByCategoryIdAndStatus(Integer categoryId, Integer status, Pageable pageable);
    List<Video> findByCategoryIdAndStatus(Long categoryId, Integer status);
    Page<Video> findByUserIdAndStatus(Long userId, Integer status, Pageable pageable);
    Page<Video> findByTagsContainingAndStatus(String tag, Integer status, Pageable pageable);

    Page<Video> findByStatusOrderByViewCountDesc(Integer status, Pageable pageable);
    List<Video> findTop15ByStatusOrderByViewCountDesc(Integer status);
    List<Video> findTop4ByStatusOrderByViewCountDesc(Integer status);

    Page<Video> findByStatusOrderByCreatedAtDesc(Integer status, Pageable pageable);
    List<Video> findTop15ByStatusOrderByCreatedAtDesc(Integer status);

    Page<Video> findByStatusAndTitleContainingOrStatusAndDescriptionContainingOrStatusAndTagsContaining(Integer status1, String keyword1, Integer status2, String keyword2, Integer status3, String keyword3, Pageable pageable);

    Optional<Video> findById(Long id);

    @Modifying
    @Query("UPDATE Video v SET v.viewCount = v.viewCount + 1 WHERE v.id = :id")
    int incrementViewCount(@Param("id") Long id);
    
    @Modifying
    @Query("UPDATE Video v SET v.viewCount = v.viewCount + :increment WHERE v.id = :id")
    int incrementViewCount(@Param("id") Long id, @Param("increment") int increment);
    
    // 统计指定状态的视频数量
    long countByStatus(Integer status);
}